var express = require('express'), app = express(),
    server = require('http').createServer(app),
    io = require('socket.io').listen(server, { log: false }),
    ent = require('ent'),
    fs = require('fs'),
	path = require('path'),
	url = require('url');
	querystring = require('querystring');

global.players = {}

var MongoClient = require('mongodb').MongoClient;
var userCollection;
MongoClient.connect("mongodb://localhost:27017/local", function(err, db) {
	if (err) {
		return console.dir(err);
	}
	userCollection = db.collection('User');
});

app.set('views', path.join(__dirname, '/views'))
.use(express.static(__dirname + '/public'))
.use(express.favicon(__dirname + '/public/favicon.ico'))
.use(express.bodyParser())
.use(express.methodOverride())
.get('/', function(req, res) {
	res.sendfile(__dirname + '/views/index.html');
})
.get('/legacy', function(req, res) {
	res.sendfile(__dirname + '/views/game.html');
})
.post('/login', function(req, res) {
	var params = querystring.parse(url.parse(req.url).query);
	userCollection.findOne({login: params['login'], password: params['password']}, function(err, item) {
		if (err) {
			return console.dir(err);
		}
		if (item) {
			res.sendfile(__dirname + '/views/game.html');
		} else {
			res.sendfile(__dirname + '/views/index.html');
		}
	});
})
.post('/register', function(req, res) {
	var params = querystring.parse(url.parse(req.url).query);
	userCollection.insert({login: params['login'], password: params['password']}, function(err, doc) {
		if (err) {
			return console.dir(err);
		} else {
			res.sendfile(__dirname + '/views/game.html');
		}
	});
});

io.set('log level', 2);

io.sockets.on('connection', function(socket, pseudo) {
	socket.emit('joueurs', global.players);

    socket.on('nouveau_joueur', function(pseudo) {
        pseudo = ent.encode(pseudo);
        socket.set('pseudo', pseudo);
		global.players[pseudo] = {
			connected: true, 
			animation: null, 
			position: {x: 0, y: 0, z: 0}, 
			rotation: {x: 0, y: 0, z: 0},
			model: 'models/male.js',
			textures: {
				body: 'textures/male_texture.png',
				eyes: 'textures/brown_eye.png'
			}
		};
		socket.broadcast.emit('nouveau_joueur', {
			name: pseudo,
			model: 'models/male.js',
			textures: {
				body: 'textures/male_texture.png',
				eyes: 'textures/brown_eye.png'
			}
		});
    });

	socket.on('sortie_joueur', function(pseudo) {
		pseudo = ent.encode(pseudo);
		global.players[pseudo].connected = false;
		socket.broadcast.emit('sortie_joueur', pseudo);
    });

	socket.on('nouveau_message', function(message) {
        socket.get('pseudo', function (error, pseudo) {
            message = ent.encode(message);
            socket.broadcast.emit('nouveau_message', {
				pseudo: pseudo, 
				message: message
			});
        });
    });

	socket.on('move_joueur', function(vector) {
        socket.get('pseudo', function (error, pseudo) {
			socket.broadcast.emit('move_joueur', {
				pseudo: pseudo, 
				x: vector.x, 
				y: vector.y, 
				z: vector.z
			});
        });
    });

	socket.on('rotate_joueur', function(vector) {
        socket.get('pseudo', function (error, pseudo) {
			socket.broadcast.emit('rotate_joueur', {
				pseudo: pseudo, 
				x: vector.x, 
				y: vector.y, 
				z: vector.z
			});
        });
    });

	socket.on('animate_joueur', function(animation) {
		if (animation) {
			animation = ent.encode(animation);
		}
		socket.get('pseudo', function (error, pseudo) {
			global.players[pseudo].animation = animation;
			socket.broadcast.emit('animate_joueur', {
				pseudo: pseudo,
				animation: animation
			});
		});
    });

	socket.on('position_joueur', function(vector) {
        socket.get('pseudo', function (error, pseudo) {
            global.players[pseudo].position.x = vector.x;
			global.players[pseudo].position.y = vector.y;
			global.players[pseudo].position.z = vector.z;
        });
    });
	socket.on('rotation_joueur', function(vector) {
        socket.get('pseudo', function (error, pseudo) {
            global.players[pseudo].rotation.x = vector.x;
			global.players[pseudo].rotation.y = vector.y;
			global.players[pseudo].rotation.z = vector.z;
        });
    });
});

server.listen(8080);
